import React from "react";

import BaseComponent from "../../../../redare/components/BaseComponent";
import PermissionPresenter from "../../.gen/presenter/component/core/PermissionPresenter";
import {Button, Checkbox, Row} from "antd";
import Grid from "../../../../redare/components/grid/Grid";
import PlatformMenuSelect from "../pmenu/PlatformMenuSelect";
import Icon from "../../../../redare/components/common/Icon";
import FunPermission from "./FunPermission";
import {isLoginUserInRootPlatform} from "../../utils/WorkbenchUtil";
import {getAbsolutePosition} from "../../../../redare/utils/DocumentUtils";

export default class RoleMenuGrid extends BaseComponent {

    static defaultProps = {
        platform: undefined,
        onMenuSelected: undefined
    };

    constructor(props) {
        super(props);
        this.presenter = new PermissionPresenter(this);
        this._isRootPlatform = isLoginUserInRootPlatform();
        this._domId = `${this.props.platform}-role-menu-grid`;
    }

    componentDidMount() {
        let grid = document.getElementById(this._domId);
        let {top} = getAbsolutePosition(grid);
        if (top) {
            this.setState({offsetTop: top + 70});
        } else {
            this.setState({offsetTop: 200});
        }
    }

    setRoleId(roleId) {
        this._form.roleId = roleId;
        this._findMenuList();
        this.setState({menuId: []});
    }

    _findMenuList() {
        let {roleId, platformMenuId} = this._form;
        if (roleId && (platformMenuId || !this._isRootPlatform)) {
            this.showLoadingIndicator('加载中...');
            this.presenter.findRoleMenuList({
                roleId,
                platformMenuId,
                enabled: true,
                excRoot: true,
                sortToTree: true
            }, {returnAll: true}, (result) => {
                this._expandedRowKeys = [];
                if (result.data) {
                    this._parseData(result.data);
                }
                this.setState({expandedRowKeys: this._expandedRowKeys});
                this.grid.setData(result.data);
            });
        } else {
            this.grid.setData(null);
        }
    }

    _parseData(data) {
        data.forEach(d => {
            this._expandedRowKeys.push(d.id);
            if ((d.children instanceof Array)) {
                if (d.children.length === 0) {
                    delete d.children;
                } else {
                    this._parseData(d.children);
                }
            }
        });
    }

    _onSelect(record, selected) {
        let menu = null;
        if (selected) {
            menu = record;
            this.setState({menuId: [record.id]});
        } else {
            this.setState({menuId: []});
        }
        if (this.props.onMenuSelected) {
            this.props.onMenuSelected(menu);
        }
    }

    _onPermissionChange(record) {
        let {menuId, adminPermission, hasPermission} = record;
        if (adminPermission) {
            this.toastInfo('管理员角色具有全部权限，不能修改');
            return;
        }
        let {roleId} = this._form;
        if (hasPermission) {
            this.presenter.delRoleMenu({roleId, menuIds: [menuId]}, null, () => {
                this.noticeSuccess('操作成功');
                this._findMenuList();
            });
        } else {
            this.presenter.addRoleMenu({roleId, menuIds: [menuId]}, null, () => {
                this.noticeSuccess('操作成功');
                this._findMenuList();
            });
        }
    }

    showLoadingIndicator(text, options = {}) {
        this.grid.showLoadingIndicator(text);
    }

    closeLoadingIndicator() {
        this.grid.closeLoadingIndicator();
    }

    render() {
        return (
            <>
                <Row style={({paddingBottom: 10})}>
                    {
                        this._isRootPlatform && (
                            <>
                                <span>菜单：</span>
                                <PlatformMenuSelect
                                    initFirstValue={true}
                                    platform={this.props.platform}
                                    allowClear={false}
                                    style={({width: 150, marginRight: 10})}
                                    onValueChange={(menuId) => {
                                        this._form.platformMenuId = menuId;
                                        this._findMenuList();
                                    }}
                                />
                            </>
                        )
                    }
                    <Button size="middle"
                            onClick={this._findMenuList.bind(this)}
                    >刷新</Button>
                </Row>
                <Grid
                    ref={(o) => {
                        this.grid = o
                    }}
                    id={this._domId}
                    scroll={{y: window.document.body.clientHeight - this.state.offsetTop || 0}}
                    expandedRowKeys={this.state.expandedRowKeys}
                    onExpand={(expanded, record) => {
                        if (expanded) {
                            this._expandedRowKeys.push(record.id);
                        } else {
                            this._expandedRowKeys = this._expandedRowKeys.filter(v => v !== record.id);
                        }
                        this.setState({expandedRowKeys: this._expandedRowKeys});
                    }}
                    rowSelection={({
                        selectedRowKeys: this.state.menuId,
                        hideDefaultSelections: true,
                        columnTitle: '选择',
                        onSelect: this._onSelect.bind(this)
                    })}
                    _onRowClick={({record}) => {
                        let selected = true;
                        let curMenuId = (this.state.menuId || [])[0];
                        if (curMenuId && curMenuId === record.id) {
                            selected = false;
                        }
                        this._onSelect(record, selected);
                    }}
                    _showPage={false}
                    _initLoading={false}
                    rowKey={(r) => r.id}
                    size="small"
                    columns={[
                        {
                            title: '菜单名称',
                            dataIndex: 'id',
                            render: (value, record) => {
                                let {iconCls, name, parentMenuId} = record;
                                let content = [];
                                if (iconCls) {
                                    content.push(
                                        <span key={0} style={({marginRight: 3})}>
                                            <Icon name={iconCls}/>
                                        </span>
                                    );
                                } else if (parentMenuId) {
                                    content.push(
                                        <span key={0} style={({width: 7, display: 'inline-block'})}/>
                                    );
                                }
                                content.push(<b key={1}>{name}</b>);
                                return content;
                            }
                        },
                        {
                            title: '权限',
                            dataIndex: 'permission',
                            align: 'center',
                            width: 80,
                            render: (value, record) => {
                                let {hasPermission} = record;
                                return (
                                    <FunPermission
                                        funId={['WebPlatformRolePermissionAddMenu', 'WebPlatformRolePermissionDelMenu']}
                                        funIdAll={true}
                                        noPermissionComponent={
                                            <Checkbox checked={hasPermission}
                                                      disabled={true}
                                            />
                                        }
                                    >
                                        <div onClick={(event) => {
                                            event.stopPropagation();
                                        }} style={({width: '100%', height: '100%'})}>
                                            <Checkbox checked={hasPermission}
                                                      onChange={this._onPermissionChange.bind(this, record)}
                                            />
                                        </div>
                                    </FunPermission>
                                );
                            }
                        }
                    ]}/>
            </>
        )
    }
}
